package com.ytktt.study.week7.task9.config;

import com.google.common.collect.Maps;
import com.ytktt.study.week7.task9.constant.DataSourceConstant;
import com.ytktt.study.week7.task9.ds.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态数据源配置
 *
 * @author ytk
 */
@Slf4j
@Configuration
public class DynamicDataSourceConfig {

    @Bean(name = "writeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikari.write")
    public DataSource writeDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "readDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikari.read")
    public DataSource readDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dynamicDataSource() {
        Map<Object, Object> targetDataSources = Maps.newHashMap();
        DataSource primaryDataSource = this.writeDataSource();
        targetDataSources.put(DataSourceConstant.WRITE_KEY, primaryDataSource);
        targetDataSources.put(DataSourceConstant.READ_KEY, this.readDataSource());
        return new DynamicDataSource(primaryDataSource, targetDataSources);
    }

    @Bean(name = "SqlSessionFactory")
    @DependsOn("dynamicDataSource")
    public SqlSessionFactory sqlSessionFactory(DataSource dynamicDataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml"));
        return bean.getObject();
    }

    @Bean(name = "writeTxManager")
    @DependsOn("writeDataSource")
    public PlatformTransactionManager writeTxManager(@Qualifier("writeDataSource") DataSource writeDataSource) {
        return new DataSourceTransactionManager(writeDataSource);
    }
}
